<template>
  <div class="template" :style="[{margin:(docItemDefClassifyData.length!=0?'50px 0':'')}]">
    <div class="top-btn">
      <div v-if="docItemDefClassifyData.length!=0&&!editShow">
        <el-button v-for="(item,index) in docItemDefClassifyData" :key="index" style="margin: 5px;"
        :type="docItemDefClassifyId==item.docItemDefClassifyId?'primary':'default'"
        size="mini"
        @click="getTemplate(item)"
        >
          {{dict_docItemDefClassify[item.docItemDefClassifyId]}}
        </el-button>
      </div>
      <el-button :type="myTemplateSeleted?'primary':'default'" size="mini" style="position: absolute;right: 10px;" @click="templateData2me">只看自己</el-button>
    </div>
    <div v-if="editShow" class="top-btn">
      <el-button @click="insertTemplate(dataList[0])" type="primary" size="mini" icon="el-icon-plus">{{dict_docItemDefClassify[docItemDefClassifyId]}}</el-button>
    </div>
    <div v-if="insertBtn" class="top-btn">
      <el-button @click="insertTemplate(dataList[0])" type="primary" size="mini" icon="el-icon-plus">新增模板</el-button>
    </div>
    <vxe-toolbar style="margin-top: 50px;">
      <template #buttons>
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
          </vxe-pager>
          <vxe-input v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
        </div>
      </template>
    </vxe-toolbar>
    <vxe-table resizable ref="XTable" max-height="530" border stripe highlight-hover-row highlight-current-row :edit-config="editShow?{trigger: 'click', mode: 'cell'}:{}"
      :loading="loading" :data="dataList" @sort-change="sortChange" @edit-closed="editClosedEvent">
      <vxe-table-column field="emp" title="上传者" sortable width="160"></vxe-table-column>
      <vxe-table-column field="content" :title="contentName" :edit-render="{name: 'input',autoselect: true, attrs: {type: 'text', placeholder: '请输入内容'}}" sortable></vxe-table-column>
      <vxe-column field="a" type="checkbox" width="60"></vxe-column>
      <vxe-table-column field="sort" title="排序(上移|下移|置顶|置底)" width="200" :visible="false">
        <template #default="{ row,$rowIndex, column }">
          <div class="up-btn">
            <i @click="sortMove('up',$rowIndex)" class="el-icon-top"></i>
            <i @click="sortMove('down',$rowIndex)" class="el-icon-bottom"></i>
            <i @click="sortMove('top',$rowIndex)" class="el-icon-download" style="transform: rotate(180deg);"></i>
            <i @click="sortMove('bottom',$rowIndex)" class="el-icon-download"></i>
          </div>
        </template>
      </vxe-table-column>
      <vxe-table-column field="b" title="操作" width="50" :visible="false">
        <template #default="{ row, column }">
          <el-button v-if="row.planTemplateId" @click="deleteEvent(row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
          <el-button v-else type="primary" size="mini" icon="iconfont icon-save" circle></el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div class="bottom-btn">
      <el-button v-if="editShow" @click="templateSort" type="primary" size="small" icon="el-icon-sort" >模板排序</el-button>
      <el-button v-if="editShow" @click="goback" type="primary" size="small" icon="el-icon-back" >返回</el-button>
      <el-button v-else @click="editTemolate" type="primary" size="small" icon="el-icon-setting" >模板管理</el-button>
      <el-button v-if="!editShow" @click="getSelectEvent" type="primary" size="small" icon="el-icon-s-promotion" >确认</el-button>
      <el-button @click="closeTemplate" type="warning" size="small" icon="el-icon-close">关闭</el-button>
    </div>
  </div>
</template>

<script>
  import {currentRoleEmployee} from "@/api/dict.js"
  import {docItemDefClassifyByDefId,plan_template,myTemplate,plan_template_insert,plan_template_update,plan_template_delete,definedTemplate} from "@/api/plan.js"
  export default {
    props: ['docItemDefId','sportId','empId'],
    data() {
      return {
        dict_docItemDefClassify: {
        	1: "一般准备阶段",
        	2: "专项准备阶段",
        	3: "赛前准备阶段",
        	4: "主要比赛阶段",
        	5: "恢复阶段",
        	6: "一般体能",
        	7: "专项体能",
        	8: "技术战术",
        	9: "运动心理",
        	10: "运动智力",
        	11: "训练内容",
        	12: "训练方法",
        	13: "练习要求及要点",
        	14: "密度及时间",
        	15: "其他",
        },
        docItemDefClassifyId: 0,
        docItemDefClassifyData: [],
        defaultTemplateData: [],
        templateData: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_emp: {},
        editShow: false,
        contentName: '内容',
        search: false,
        myTemplateSeleted: false,
        isSort: false,
      }
    },
    computed: {
      insertBtn() {
        if(this.docItemDefClassifyData.length==0&&this.editShow){
          return true
        }else{
          return false
        }
      }
    },
    watch: {
      docItemDefId(newValue, oldValue) {
        this.docItemDefClassifyByDefId()
      },
      docItemDefClassifyData(newValue, oldValue) {
        if(newValue.length == 0){
          this.docItemDefClassifyId = 0
        }
      },
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.docItemDefClassifyByDefId()
      })
    },
    methods: {
      sortMove(e,index) {
        if(e=='up'){
          if(index!=0){
            this.defaultTemplateData[index] = this.defaultTemplateData.splice(index-1, 1, this.defaultTemplateData[index])[0]
          }
        }else if(e=='down') {
          if(index!=this.defaultTemplateData.length-1){
            this.defaultTemplateData[index] = this.defaultTemplateData.splice(index+1, 1, this.defaultTemplateData[index])[0]
          }
        }else if(e=='top') {
          let item = this.defaultTemplateData.splice(index,1)
          this.defaultTemplateData.unshift(item[0])
        }else if(e=='bottom') {
          let item = this.defaultTemplateData.splice(index,1)
          this.defaultTemplateData.push(item[0])
        }
        this.isSort = true
        this.findList()
      },
      templateSortSave() {
        this.defaultTemplateData.forEach((item,index)=>{
          this.plan_template_update_save(item,index)
        })
      },
      plan_template_update_save(item,index) {
        return new Promise((resolve,reject)=>{
          plan_template_update({ planTemplateId: item.planTemplateId,seq: index+1}).then(res=>{
            resolve()
          })
        })
      },
      templateSort() {
        this.page.pageSize = this.defaultTemplateData.length
        this.page.currentPage = 1
        this.findList()
        this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('sort'))
      },
      templateData2me() {
        if(!this.myTemplateSeleted){
          this.templateData = this.defaultTemplateData.filter(item=>{
            return item.empId != -1
          })
          this.myTemplateSeleted = true
        }else{
          this.templateData = this.defaultTemplateData
          this.myTemplateSeleted = false
        }
        this.findList()
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          plan_template_delete({planTemplateId:row.planTemplateId}).then(res=>{
            if(res.code === 200 ){
              this.$message.success('删除成功！')
              this.editTemolate()
            }else{
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editClosedEvent({ row, column }) {
        const $table = this.$refs.XTable
        const field = column.property
        const cellValue = row[field]
        if(!cellValue){
          this.$message.warning('没有输入内容')
          return
        }
        // 添加模板
        if(!row.planTemplateId) {
          let data = {
            docItemDefId: this.docItemDefId,
            docItemDefClassifyId: this.docItemDefClassifyId,
          }
          if(this.sportId) data.sportId = this.sportId
          if(this.insertBtn){
            data.docItemDefClassifyId = 0
          }
          data[field] = cellValue
          plan_template_insert(data).then(res=>{
            if(res.code === 200) {
              setTimeout(()=>{
                row.planTemplateId = res.data.planTemplateId
                res.data.emp = this.dict_emp[res.data.empId]
                this.templateData.unshift(res.data)
                // this.defaultTemplateData.unshift(res.data)
                this.page.totalResult+=1
              },500)
              this.$message.success('添加成功！')
            }else{
              this.$message.error(res.message)
            }
          })
        }else{
          // 修改模板
          let data = {
            planTemplateId: row.planTemplateId,
          }
          if(this.sportId) data.sportId = this.sportId
          data[field] = cellValue
          plan_template_update(data).then(res=>{
            if(res.code === 200) {
              this.templateData.forEach(item=>{
                if(item.planTemplateId == row.planTemplateId){
                  item.content = res.data.content
                }
              })
              this.$message.success('修改成功！')
            }else{
              this.$message.error(res.message)
            }
          })
        }
      },
      // 添加一行
      async insertTemplate(row) {
        const $table = this.$refs.XTable
        const record = {
          docItemDefClassifyId: this.docItemDefClassifyId,
          docItemDefId: this.docItemDefId,
          content: '',
          empId: this.empId,
          emp: this.dict_emp[this.empId],
        }
        if(this.sportId) record.sportId = this.sportId
        const { row: newRow } = await $table.insertAt(record, row)
        await $table.setActiveCell(newRow, 'content')
      },
      // 返回
      goback() {
        if(this.isSort){
          this.templateSortSave()
        }
        this.filterName = ''
        this.editShow = false
        this.contentName = '内容'
        this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('a'))
        this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('b'))
        this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('sort'))
        this.plan_template()
      },
      // 模板管理
      editTemolate() {
        this.filterName = ''
        this.editShow = true
        this.insertShow = true
        this.contentName = '内容(可直接点击修改)'
        this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('a'))
        this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('b'))
        let data = {
          docItemDefId: this.docItemDefId,
          docItemDefClassifyId: this.docItemDefClassifyId
        }
        if(this.sportId) data.sportId = this.sportId
        myTemplate(data).then(res=>{
          if(res.code === 200 && res.data.length != 0) {
            res.data.forEach(item=>{
              if(item.empId == -1){
                item.emp = '系统内容'
              }else{
                item.emp = this.dict_emp[item.empId]
              }
            })
            res.data = res.data.sort((a,b)=>{
              return a.seq-b.seq
            })
            this.defaultTemplateData = res.data
            this.templateData = res.data
            if(this.myTemplateSeleted){
              this.templateData = this.defaultTemplateData.filter(item=>{
                return item.empId != -1
              })
            }
            this.searchProps = ['emp','content']
            this.page = {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
              }
          }else{
            this.templateData = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      // 关闭
      closeTemplate() {
        if(this.isSort){
          this.templateSortSave()
        }
        this.$emit('templateClose')
      },
      // 确认
      getSelectEvent () {
        let selectRecords = this.$refs.XTable.getCheckboxRecords()
        if(selectRecords.length != 0) {
          let selectArr = []
          selectRecords.forEach(item=>{
            selectArr.push(item.content)
          })
          let str = selectArr.join('<p>')
          let title = this.dict_docItemDefClassify[this.docItemDefClassifyId]
          let templateStr = (title?'<p>'+title+':</p>':'') +'<p>'+str+'</p>'
          this.$emit('getTemplateName',templateStr)
          this.$refs.XTable.clearCheckboxRow()
        }else{
          this.$emit('templateClose')
        }
      },
      getTemplate(item) {
        this.docItemDefClassifyId = item.docItemDefClassifyId
        this.plan_template()
      },
      plan_template() {
        let data = {
          docItemDefId: this.docItemDefId,
          docItemDefClassifyId: this.docItemDefClassifyId
        }
        if(this.sportId) data.sportId = this.sportId
        this.templateData = []
        plan_template(data).then(res=>{
          if(res.code === 200 ){
            if(res.data.length != 0) {
              res.data.forEach(item=>{
                if(item.empId == -1){
                  item.emp = '系统内容'
                }else{
                  item.emp = this.dict_emp[item.empId]
                }
              })
              res.data = res.data.sort((a,b)=>{
                return a.seq-b.seq
              })
              this.defaultTemplateData = res.data
              this.templateData = res.data
              if(this.myTemplateSeleted){
                this.templateData = this.defaultTemplateData.filter(item=>{
                  return item.empId != -1
                })
              }
              this.searchProps = ['emp','content']
              this.findList()
            }else{
              this.defaultTemplateData = []
              this.templateData = []
            }
          }else{
            this.$message.error(res.message)
          }
        }).then(()=>{
          this.findList()
        })
      },
      definedTemplate() {
        let data = {
          docItemDefId: this.docItemDefId,
          docItemDefClassifyId: 0
        }
        if(this.sportId) data.sportId = this.sportId
        this.templateData = []
        definedTemplate(data).then(res=>{
          if(res.code === 200) {
            if(res.data.length != 0) {
              res.data.forEach(item=>{
                if(item.empId == -1){
                  item.emp = '系统内容'
                }else{
                  item.emp = this.dict_emp[item.empId]
                }
              })
              res.data = res.data.sort((a,b)=>{
                return a.seq-b.seq
              })
              this.defaultTemplateData = res.data
              this.templateData = res.data
              if(this.myTemplateSeleted){
                this.templateData = this.defaultTemplateData.filter(item=>{
                  return item.empId != -1
                })
              }
              this.searchProps = ['emp','content']
            }else{
              this.defaultTemplateData = []
              this.templateData = []
            }
          }
        }).then(()=>{
          this.findList()
        })
      },
      docItemDefClassifyByDefId() {
        this.goback()
        this.docItemDefClassifyId = 0
        this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        }
        docItemDefClassifyByDefId({docItemDefId:this.docItemDefId}).then(res=>{
          if(res.code === 200) {
            if(res.data.length != 0) {
              this.docItemDefClassifyData = res.data
              this.docItemDefClassifyId = res.data[0].docItemDefClassifyId
              this.plan_template()
            }else{
              this.docItemDefClassifyData = []
              this.definedTemplate()
            }
          }else{
            this.$message.error(res.message)
          }
        })
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          currentRoleEmployee().then(res=>{
            this.dict_emp = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.templateData.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.templateData
          this.findList()
        }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.templateData.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.templateData.length
          this.dataList = this.templateData.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .template{
    .top-btn{
      width: 100%;
      min-height: 50px;
      line-height: 50px;
      display: flex;
      align-items: center;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 9999;
      background-color: #ffffff;
      padding: 0 20px;
      flex-wrap: wrap;
    }
    .up-btn{
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      right: 0;
      i{
        margin: 0 15px;
        cursor: pointer;
        font-size: 120%;
        &:hover{
          color: #000000;
          font-weight: bold;
        }
      }
    }
    .bottom-btn{
      width: 100%;
      height: 50px;
      line-height: 50px;
      position: absolute;
      bottom: 0;
      right: 0;
      background-color: #ffffff;
      z-index: 9999;
      text-align: right;
      padding: 0 20px;
    }
  }

</style>
